// pages/login/login.js
import Toast from '@vant/weapp/toast/toast';
import Dialog from '@vant/weapp/dialog/dialog';
import { userRequest } from "../../utils/util";
const app = getApp();
// 提取角色判断逻辑到单独的函数
function getIndexUrlByRole(role) {
    if (role == '销售员') {
        return "/templates/salesman/pages/index/index";
    } else if (role == '配送司机') {
        return "/templates/deliver/pages/index/index";
    } else if (role == '仓库库管') {
        return "/templates/warehouse/pages/warehouse/index";
    } else {
        return ''
    }
}
Page({
    /**
     * 页面的初始数据
     */
    data: {
        saveAccount: false,
        agreementChecked: false,
        role: '销售员', /*原 sales*/
        username: '',
        password: '',
        iconName: 'eye-o',
        isPassword: true,//显示密码
        level: '',
    },
    onLoad(options) {
        // 从本地存储中获取传递过来的数据
        let that = this
        let role = wx.getStorageSync('role')
        console.log(role)
        let indexUrl = getIndexUrlByRole(role);
        let now = (new Date().getTime()) / 1000;
        let expiration_time = wx.getStorageSync('expiration_time')
        if (expiration_time && now < expiration_time) {
            wx.reLaunch({
                url: indexUrl
            })
            return
        }
        let saveAccount = that.usergetStorageSync('saveAccount', false)
        let agreementChecked = that.usergetStorageSync('saveAgreementChecked', false)
        let username = that.usergetStorageSync('username', '')
        let password = that.usergetStorageSync('password', '')

        this.setData({
            saveAccount,
            agreementChecked,
            username,
            password,
            role
        })
    },
    async formSub(e) {
        let role = this.data.role
        console.log(role)
        let saveAccount = this.data.saveAccount
        let { username, password, agreementChecked } = e.detail.value

        let url = ''
        let index = getIndexUrlByRole(role);
        if (role === '销售员') {
            url = app.globalData.API + '/sales/index/app-login'
            // index = "/templates/salesman/pages/index/index"
        } else if (role === '配送司机') {
            url = app.globalData.API + '/delivery/index/app-login'
        } else if (role === '仓库库管') {

            url = app.globalData.API + '/delivery/index/app-login'
        }
        if (!agreementChecked) {
            Toast('请点击下方我已阅读');
            return false;
        }
        const data = {
            mobile: username,
            password: password
        }
        try {
            wx.showLoading({
                title: '正在登录...'
            })
            const res = await userRequest(url, 'POST', data);
            console.log(res)
            console.log(res.data.member.level)
            wx.hideLoading()
            if (res.code === 200) {
                let now = (new Date().getTime()) / 1000;
                let refresh_token = res.data['refresh_token'];
                let access_token = res.data['access_token'];
                let expiration_time = res.data['expiration_time'] + now;
                let user = res.data['member'];
                let level = res.data['member'].level;
                wx.setStorageSync('refresh_token', refresh_token);
                wx.setStorageSync('access_token', access_token);
                wx.setStorageSync('expiration_time', expiration_time);
                wx.setStorageSync('level', level);
                wx.setStorageSync("role", role); // 兼容之前的
                wx.setStorageSync('user', user)

                if (!saveAccount) {
                    username = '';
                    password = '';
                    agreementChecked = false;
                }

                wx.setStorageSync('saveAccount', saveAccount);
                wx.setStorageSync('username', username);
                wx.setStorageSync('password', password);
                wx.setStorageSync('saveAgreementChecked', agreementChecked);

                app.session = {
                    refresh_token,
                    access_token,
                    expiration_time,
                    level,
                    role,
                    user
                };

                wx.setStorageSync('session', app.session);
                setTimeout(() => {
                    wx.reLaunch({
                        url: index
                    });
                }, 1000);
            } else {
                wx.showToast({
                    title: res.data.message,
                    icon: 'error',
                    duration: 2000
                });
            }
        } catch (error) {

            wx.showToast({
                title: '登入失败',
                icon: 'error',
                duration: 2000
            });
        }

    },
    // 点击返回上一页
    goBack: function () {
        wx.navigateBack({
            delta: 1
        });
    },
    // 点击显示密码
    showPassword: function () {
        console.log('点击眼睛了')
        this.data.isPassword = !this.data.isPassword
        this.setData({
            iconName: this.data.iconName === 'eye-o' ? 'closed-eye' : 'eye-o',
            isPassword: this.data.isPassword,
        });
    },
    //这是点击阅读来回切换
    checkedTap(e) {
        this.setData({
            agreementChecked: !this.data.agreementChecked
        })
    },
    tap_saveAccount(e) {
        let saveAccount = this.data.saveAccount;
        this.setData({
            saveAccount: !saveAccount
        })
    },

    //点击弹窗
    showUserAgreement() {
        Dialog.alert({
            title: '用户隐私',
            message: '富多多助手仅针对公司内部人员使用，不对外开放。',
            showConfirmButton: true,
        }).then(() => {
            // on close
        });

    },
    //点击弹窗
    showPrivacyAgreement() {
        Dialog.alert({
            title: '隐私协议',
            message: '富多多助手在使用中会获取用户的定位信息。',
            showConfirmButton: true,
        }).then(() => {
            // on close
        });

    },
    /**
     * 生命周期函数--监听页面加载
     * 判断缓存中是否存在对应的身份跳转对应页面(登录页拦截)
     */

    usergetStorageSync(key, defaultValue = undefined) {
        const value = wx.getStorageSync(key);
        return value ? value : defaultValue;
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    },

})
